﻿// ***********************************************************************
// Provided for Informational Purposes Only
//
// Apache 2.0 License
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY 
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR 
// PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
// ***********************************************************************
// Assembly  : ContractMeow.ModernApp
// File      : LoginViewModel.cs
//
// ***********************************************************************
using Caliburn.Micro;
using ContractMeow.Api.Exceptions;
using ContractMeow.Data.WinRT;
using ContractMeow.ModernApp.Views;

namespace ContractMeow.ModernApp.ViewModels
{
	public class LoginViewModel : ViewModelBase
	{
		private readonly IAuthRepository _authRepository;
		private readonly IUserRepository _userRepository;

		public LoginViewModel(INavigationService navigationService, IAuthRepository authRepository, IUserRepository userRepository, IStateManager stateManager)
			: base(navigationService, stateManager)
		{
			_authRepository = authRepository;
			_userRepository = userRepository;
		}

		private string _email;
		public string Email
		{
			get { return _email; }
			set
			{
				_email = value;
				NotifyOfPropertyChange(() => Email);
				NotifyOfPropertyChange(() => CanLogin);
			}
		}

		private string _password;
		public string Password
		{
			get { return _password; }
			set
			{
				_password = value;
				NotifyOfPropertyChange(() => Password);
				NotifyOfPropertyChange(() => CanLogin);
			}
		}

		private bool _hasErrored;
		public bool HasErrored
		{
			get { return _hasErrored; }
			set
			{
				_hasErrored = value;
				NotifyOfPropertyChange(() => HasErrored);
			}
		}

		public async void Login()
		{
			HasErrored = false;
			IsBusy = true;

			try
			{
				var credentials = await _authRepository.LoginAsync(Email, Password); /* Login via Yammer authentication */

				if (credentials != null)
					NavigationService.Navigate<MyContractsView>();
			}
			catch (UnauthorizedException)
			{
				HasErrored = true;
			}

			IsBusy = false;
		}

		public bool CanLogin
		{
			get
			{
				return !string.IsNullOrWhiteSpace(Email) && !string.IsNullOrWhiteSpace(Password); 
			}
		}

		public void Attributions()
		{
			NavigationService.Navigate<AttributionsView>();

		}
	}
}
